package com.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.action.Action;
import com.util.ActionMapper;
import com.util.FormUtil;
import com.util.XMLBean;
import com.vo.ActionForm;

public class ActionServlet extends HttpServlet {
    
    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("text/html; charset=UTF-8");
                String path=getPath(request.getServletPath());
                
                Map<String,XMLBean> map=(Map<String, XMLBean>) this.getServletContext().getAttribute("struts");
                
                XMLBean bean=map.get(path);
                
                String fromClsss=bean.getFromClass();
                
                ActionForm form=FormUtil.fillBean(fromClsss,request);//获取acitonForm
                
               String actionType=bean.getActionClass();
               
               String requestUrl="";
               
               String forwardUrl="";
               
               Action action=null;
               try {
                    Class c=Class.forName(actionType);
                    
                    action=(Action) c.newInstance();
                    
                    requestUrl= action.execute(form,request,bean.getMap());
                    
                    for (Entry<String, String> m : bean.getMap().entrySet()) {
                        if(m.getKey().contains(requestUrl)){
                            forwardUrl=m.getValue();
                            break;
                        }
                    }
                    
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
               
               request.getRequestDispatcher(forwardUrl).forward(request, response);
               
                
                
    }
    
    

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

            this.doGet(request, response);
    }

    private String getPath(String path) {
        
        return path.split("\\.")[0];
    }

}
